package cn.eleven.service;

import cn.eleven.dao.UserDAO;
import cn.eleven.dao.impl.UserDAOImpl;
import cn.eleven.entity.User;
import cn.eleven.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用户服务类
 */
public class UserService {
    private final UserDAO userDAO = new UserDAOImpl();

    /**
     * 用户登录验证
     * @param username 用户名
     * @param password 密码
     * @return 用户对象，如果验证失败返回null
     */
    public User authenticate(String username, String password) {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            return userDAO.findByUsernameAndPassword(conn, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            DBUtil.close(conn, null, null);
        }
    }

    /**
     * 根据用户ID查找用户
     * @param userId 用户ID
     * @return 用户对象，如果未找到返回null
     */
    public User findUserById(int userId) {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            return userDAO.findById(conn, userId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            DBUtil.close(conn, null, null);
        }
    }

    /**
     * 更新用户的房间占用信息
     * @param userId 用户ID
     * @param roomName 房间名称
     * @return 如果更新成功返回true，否则返回false
     */
    public void updateRoomOccupied(int userId, String roomName) {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            userDAO.updateUserRoomOccupied(conn, userId, roomName);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, null, null);
        }
    }

    /**
     * 清除用户的房间占用信息
     * @param userId 用户ID
     * @return 如果清除成功返回true，否则返回false
     */
    public void clearRoomOccupied(int userId) {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            userDAO.clearUserRoomOccupied(conn, userId);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, null, null);
        }
    }

    /**
     * 获取用户余额
     * @param userId 用户ID
     * @return 余额
     */
    public double getUserBalance(int userId) {
        Connection conn = null;
        double balance = 0;
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT ` user_balance` FROM user WHERE id = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                balance = rs.getDouble("balance");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, null, null);
        }
        return balance;
    }

    /**
     * 充值余额
     * @param userId 用户ID
     * @param amount 充值金额
     * @return 是否充值成功
     */
    public boolean rechargeBalance(int userId, double amount) {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE user SET user_balance = user_balance + ? WHERE id = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setDouble(1, amount);
            pstmt.setInt(2, userId);
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, null, null);
        }
    }

    public void deductBalance(int userId, int amount) throws SQLException {
        String sql = "UPDATE user SET user_balance = user_balance - ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, amount);
            pstmt.setInt(2, userId);
            pstmt.executeUpdate();
        }
    }

    /**
     * 检查用户名是否已存在
     */
    public boolean isUsernameTaken(String username) throws SQLException {
        return userDAO.isUserExists(username);
    }

    /**
     * 注册用户
     */
    public void registerUser(User user) throws SQLException {
        userDAO.addUser(user);
    }

}